package org.sunyaxing.transflow.transflowapp.factory;

import cn.hutool.core.annotation.AnnotationUtil;
import cn.hutool.core.lang.ClassScanner;
import jakarta.annotation.PostConstruct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.sunyaxing.transflow.api.common.ano.Extension;
import org.sunyaxing.transflow.api.extensions.ExtensionLifecycle;
import org.sunyaxing.transflow.api.extensions.base.ExtensionContext;

import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

@Service
public class TransFlowPluginManager implements PluginManager {

    private static final Logger log = LoggerFactory.getLogger(TransFlowPluginManager.class);
    @Autowired
    private TransFlowExtensionFactory transFlowExtensionFactory;
    /**
     * 所有的插件
     */
    private Map<String, Class<? extends ExtensionLifecycle>> extensions = new ConcurrentHashMap<>();

    @PostConstruct
    public void scanPlugins() {
        Set<Class<?>> classes = ClassScanner.scanPackageByAnnotation("org.sunyaxing.transflow.transflowapp.plugins", Extension.class);
        classes.forEach(tclass -> {
            Extension extension = AnnotationUtil.getAnnotation(tclass, Extension.class);
            if (Objects.isNull(extension)) {
                log.error("{} 没有添加 @Extension 注解", tclass.getName());
            } else {
                String pluginId = extension.value();
                if (extensions.containsKey(pluginId)) {
                    log.error("{} 插件已经存在,可能重名", pluginId);
                } else {
                    if (ExtensionLifecycle.class.isAssignableFrom(tclass)) {
                        extensions.put(extension.value(), (Class<? extends ExtensionLifecycle>) tclass);
                    } else {
                        log.error("{} 不是 ExtensionLifecycle 的子类", tclass.getName());
                    }
                }
            }
        });
    }

    @Override
    public ExtensionLifecycle createByPluginId(ExtensionContext extensionContext, String pluginId) {
        Class<? extends ExtensionLifecycle> extensionClass = extensions.get(pluginId);
        return transFlowExtensionFactory.create(extensionContext, extensionClass);
    }

    @Override
    public Map<String, Class<? extends ExtensionLifecycle>> getPluginsMap() {
        return extensions;
    }

    @Override
    public Class<? extends ExtensionLifecycle> getPlugin(String pluginId) {
        return extensions.get(pluginId);
    }
}
